package org.surelink.radius.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.surelink.radius.RadiusConfig;

import javax.annotation.PostConstruct;
import java.util.concurrent.*;

/**
 * 任务调度服务
 */
@Service
public class TaskService
{

    private static final Log log         = LogFactory.getLog(TaskService.class);
    private ExecutorService worker;
    private ScheduledExecutorService taskWorker;
    @Autowired
    private RadiusConfig radiusConfig;

    public TaskService()
    {
        worker      = Executors.newCachedThreadPool();
        taskWorker  = Executors.newScheduledThreadPool(5);
    }

    /**
     * 初始化任务
     */
    @PostConstruct
    public void initTasks(){

    }


    /**
     * 间隔周期执行任务
     * @param command
     * @param initialDelay
     * @param delay
     * @param unit
     */
    public void scheduleWithFixedDelay(Runnable command,
                             long initialDelay,
                             long delay,
                             TimeUnit unit)
    {
        taskWorker.scheduleWithFixedDelay(command, initialDelay, delay, unit);
    }

    /**
     * 执行周期性任务
     * @param command
     * @param initialDelay
     * @param period
     * @param unit
     */
    public void scheduleAtFixedRate(Runnable command,
                                       long initialDelay,
                                       long period,
                                       TimeUnit unit)
    {
        taskWorker.scheduleAtFixedRate(command, initialDelay, period, unit);
    }


    /**
     * 执行异步任务
     * @param handler
     */
    public void execute(Runnable handler)
    {
        worker.execute(handler);
    }

    /**
     * 执行批量异步任务
     * @param handlers
     */
    public void execute(Runnable[] handlers)
    {
        for(Runnable handler : handlers)
        {
            worker.execute(handler);
        }
    }

    /**
     * 执行异步任务，返回future任务
     * @param call
     * @param <T>
     * @return
     */
    public <T> Future<T> execute(Callable<T> call){
        return worker.submit(call);
    }




}
